<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/22 0022
 * Time: 上午 9:27
 */

namespace app\admin\controller;


use app\admin\model\BannerModel;
use app\admin\validate\BannerValidate;
use think\Request;

class Banner extends Base
{
    /**
     * 轮播图管理渲染
     * @return mixed
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 轮播图遍历
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function getBannerAll(Request $request)
    {
        if ($request->isAjax()) {
            $limit = $request->param("limit");
            $model = new BannerModel();
            $result  = $model->order("sort","DESC")
                ->paginate($limit);

            foreach ($result as $key => $value) {
                $result[$key]["title"] = $value["article"]["title"];
            }
            return json(["code" => 0, "msg" => "ok","count" => $result->total() ,"data" => $result->items()]);
        }
    }


    /**
     * 修改轮播图
     * @param Request $request
     * @return mixed
     */
    public function edit(Request $request)
    {
        $article_id = $request->param("id");
        $data = BannerModel::getBannerFind($article_id);
        $this->assign("data",$data);
        return $this->fetch();
    }

    /**
     * 修改轮播图 单条
     * @param Request $request
     * @return \think\response\Json
     */
    public function editBanner(Request $request)
    {
        if ($request->isAjax()) {
            $data = $request->param();
            $validate = new BannerValidate();
            if (!$validate->check($data)) {
                return json(["code" => 403, "msg" => "验证失败","data" => $validate->getError() ,"token" => $request->token()]);
            }
            $result = BannerModel::editBannerFind($data);
            if (!$result) {
                return json(["code" => 403, "msg" => "修改失败","data" =>  "修改失败" ,"token" => $request->token()]);
            }
            return json(["code" => 1, "msg" => "修改成功"]);
        }
    }

    /**
     * 修改状态
     * @param Request $request
     * @return \think\response\Json
     */
    public function updateStatus(Request $request)
    {
        if ($request->isAjax()) {
            $id = $request->param("id");
            $status = $request->param("status");

            $result = BannerModel::updateStatus($id,$status);

            if ($result !== true) {
                return json(["code" => 403,"msg" => $status == 1 ? "禁用失败" : "启用失败"]);
            }
            return json(["code" => 1,"msg" => "更改成功"]);
        }
    }

}